package com.zhiche.wms.service.opbaas.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.google.common.collect.Maps;
import com.zhiche.wms.core.supports.BaseException;
import com.zhiche.wms.core.supports.enums.InterfaceEventEnum;
import com.zhiche.wms.core.supports.enums.InterfaceVisitTypeEnum;
import com.zhiche.wms.core.supports.enums.TableStatusEnum;
import com.zhiche.wms.domain.mapper.otm.OtmOrderReleaseMapper;
import com.zhiche.wms.domain.model.opbaas.OpDeliveryPoint;
import com.zhiche.wms.domain.model.opbaas.StatusLog;
import com.zhiche.wms.domain.model.otm.OtmOrderRelease;
import com.zhiche.wms.domain.model.otm.OtmShipment;
import com.zhiche.wms.domain.model.outbound.OutboundNoticeLine;
import com.zhiche.wms.domain.model.sys.User;
import com.zhiche.wms.domain.model.sys.UserDeliveryPoint;
import com.zhiche.wms.dto.opbaas.paramdto.AppCommonQueryDTO;
import com.zhiche.wms.dto.opbaas.paramdto.OrderReleaseParamDTO;
import com.zhiche.wms.dto.opbaas.resultdto.ReleaseWithShipmentDTO;
import com.zhiche.wms.dto.opbaas.resultdto.ShipmentForShipDTO;
import com.zhiche.wms.service.common.IntegrationService;
import com.zhiche.wms.service.constant.PutAwayType;
import com.zhiche.wms.service.constant.SourceSystem;
import com.zhiche.wms.service.dto.OTMEvent;
import com.zhiche.wms.service.dto.ShipParamDTO;
import com.zhiche.wms.service.opbaas.ExceptionToOTMService;
import com.zhiche.wms.service.opbaas.IDeliveryPointService;
import com.zhiche.wms.service.opbaas.IOrderReleaseService;
import com.zhiche.wms.service.opbaas.IStatusLogService;
import com.zhiche.wms.service.otm.IOtmShipmentService;
import com.zhiche.wms.service.outbound.IOutboundNoticeLineService;
import com.zhiche.wms.service.outbound.IOutboundPrepareHeaderService;
import com.zhiche.wms.service.outbound.IOutboundShipLineService;
import com.zhiche.wms.service.sys.IUserDeliveryPointService;
import com.zhiche.wms.service.sys.IUserService;
import com.zhiche.wms.service.utils.BusinessNodeExport;
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 运单 服务实现类
 * </p>
 *
 * @author user
 * @since 2018-05-24
 */
@Service
public class OrderReleaseServiceImpl extends ServiceImpl<OtmOrderReleaseMapper, OtmOrderRelease> implements IOrderReleaseService {
    @Autowired
    private IUserService userService;
    @Autowired
    private IntegrationService integrationService;
    @Autowired
    private IOtmShipmentService shipmentService;
    @Autowired
    private BusinessNodeExport nodeExport;
    @Autowired
    private IStatusLogService statusLogService;
    @Autowired
    private IOutboundNoticeLineService outboundNoticeLineService;
    @Autowired
    private IOutboundShipLineService outboundShipLineService;
    @Autowired
    private IOutboundPrepareHeaderService prepareHeaderService;
    @Autowired
    private IUserDeliveryPointService userDeliveryPointService;
    @Autowired
    private IDeliveryPointService deliveryPointService;
    @Autowired
    private ExceptionToOTMService exceptionToOTMService;

    @Override
    public Page<OrderReleaseParamDTO> queryOrderReleaseList(Page<OrderReleaseParamDTO> page) {
        User loginUser = userService.getLoginUser();
        if (loginUser == null) {
            throw new BaseException("请登录后进行该操作");
        }
        Wrapper<UserDeliveryPoint> userDeliveryPointWrapper = new EntityWrapper<>();
        userDeliveryPointWrapper.eq("user_id", loginUser.getId());
        List<UserDeliveryPoint> userDeliveryPoints = userDeliveryPointService.selectList(userDeliveryPointWrapper);
        if (CollectionUtils.isEmpty(userDeliveryPoints)) {
            throw new BaseException("未配置发车点,不能进行此操作");
        }
        ArrayList<Object> PointIds = new ArrayList<>();
        for (UserDeliveryPoint userDeliveryPoint : userDeliveryPoints) {
            PointIds.add(userDeliveryPoint.getPointId());
        }
        Wrapper<OpDeliveryPoint> opDeliveryPointWrapper = new EntityWrapper<>();
        opDeliveryPointWrapper.in("id", PointIds);
        List<OpDeliveryPoint> opDeliveryPoints = deliveryPointService.selectList(opDeliveryPointWrapper);
        ArrayList<String> Points = new ArrayList<>();
        for (OpDeliveryPoint opDeliveryPoint : opDeliveryPoints) {
            Points.add(opDeliveryPoint.getCode());
        }
        Wrapper<OrderReleaseParamDTO> ew = new EntityWrapper<>();
        Map<String, Object> condition = page.getCondition();
        ew.in("origin_location_gid", Points);
        if (condition != null) {
            if (condition.containsKey("vin") && Objects.nonNull(condition.get("vin"))) {
                String vin = condition.get("vin").toString();
                String[] split = vin.split(",");
                List<String> vins = Arrays.asList(split);
                ew.in("vin", vins).orNew().like("vin", vin);
            }
            if (condition.containsKey("boundType") && Objects.nonNull(condition.get("boundType"))) {
                ew.eq("bound_type", condition.get("boundType"));
            }
            if (condition.containsKey("plateNo") && Objects.nonNull(condition.get("plateNo"))) {
                ew.like("plate_no", condition.get("plateNo").toString());
            }
            if (condition.containsKey("originLocationName") && Objects.nonNull(condition.get("originLocationName"))) {
                ew.like("origin_location_name", condition.get("originLocationName").toString());
            }
            if (condition.containsKey("destLocationName") && Objects.nonNull(condition.get("destLocationName"))) {
                ew.like("dest_location_name", condition.get("destLocationName").toString());
            }
            if (condition.containsKey("startDate") && Objects.nonNull(condition.get("startDate"))) {
                ew.ge("gmt_create", condition.get("startDate").toString());
            }
            if (condition.containsKey("endDate") && Objects.nonNull(condition.get("endDate"))) {
                ew.le("gmt_create", condition.get("endDate").toString());
            }
        }
        ew.ne("shipmentStatus", TableStatusEnum.STATUS_50.getCode());
        ew.orderBy("gmt_create");
        List<OrderReleaseParamDTO> dtoList = this.baseMapper.queryOrderReleaseList(page, ew);
        page.setRecords(dtoList);
        return page;
    }

    /**
     * 装车交验 - 查询列表
     */
    @Override
    public Page<ReleaseWithShipmentDTO> queryReleaseShipList(Page<ReleaseWithShipmentDTO> page) {
        if (page == null) {
            throw new BaseException("参数page不能为空");
        }
        Map<String, Object> condition = page.getCondition();
        if (condition == null || condition.isEmpty()) {
            throw new BaseException("参数不能为空");
        }
        User loginUser = userService.getLoginUser();
        if (loginUser == null) {
            throw new BaseException("请登录后进行该操作");
        }
        Object key = condition.get("key");
        if (key == null || StringUtils.isBlank(key.toString())) {
            throw new BaseException("查询参数不能为空");
        }
        EntityWrapper<ReleaseWithShipmentDTO> ew = new EntityWrapper<>();
        ew.isNotNull("userId")
                .eq("is_ship", TableStatusEnum.STATUS_1.getCode())
                .ne("status", TableStatusEnum.STATUS_50.getCode())
                .eq("userCode", loginUser.getCode())
                .andNew()
                .like("cus_order_no", key.toString())
                .or()
                .like("shipment_gid", key.toString())
                .or()
                .like("cus_waybill_no", key.toString())
                .or()
                .like("vin", key.toString())
                .orderBy("gmt_create", false)
                .orderBy("id", false);
        List<ReleaseWithShipmentDTO> data = baseMapper.queryReleaseShipList(page, ew);
        if (CollectionUtils.isEmpty(data)) {
            throw new BaseException("为查询到对应发运数据");
        }
        page.setRecords(data);
        return page;
    }

    /**
     * 查询装车发运详细信息
     */
    @Override
    public ReleaseWithShipmentDTO getReleaseShipDetail(AppCommonQueryDTO dto) {
        if (dto == null) {
            throw new BaseException("参数不能为空");
        }
        Map<String, String> condition = dto.getCondition();
        if (condition == null || condition.isEmpty()) {
            throw new BaseException("查询参数不能为空");
        }
        String visitType = condition.get("visitType");
        String key = condition.get("key");
        User loginUser = userService.getLoginUser();
        if (loginUser == null) {
            throw new BaseException("请登录后进行该操作");
        }
        if (StringUtils.isBlank(visitType)) {
            throw new BaseException("访问方式不能为空");
        }
        if (StringUtils.isBlank(key)) {
            throw new BaseException("key不能为空");
        }
        if (InterfaceVisitTypeEnum.CLICK_TYPE.getCode().equals(visitType)) {
            ReleaseWithShipmentDTO detailClick = getDetailClick(key, loginUser);
            String send = exceptionToOTMService.isSend(detailClick.getVin(), detailClick.getOriginLocationName());
            if (StringUtils.isNotBlank(send)) detailClick.setIsCanSend(send);
            return detailClick;
        } else if (InterfaceVisitTypeEnum.SCAN_TYPE.getCode().equals(visitType)) {
            //支持qrCode 车架号  订单号 扫码
            ReleaseWithShipmentDTO detailScan = getDetailScan(key, loginUser);
            String send = exceptionToOTMService.isSend(detailScan.getVin(), detailScan.getOriginLocationName());
            if (StringUtils.isNotBlank(send)) detailScan.setIsCanSend(send);
            return detailScan;
        } else {
            throw new BaseException("不支持的访问方式");
        }
    }

    /**
     * 装车交验确认
     */
    @Override
    public OtmOrderRelease updateReleaseShip(AppCommonQueryDTO dto) {
        if (dto == null) {
            throw new BaseException("参数不能为空");
        }
        Map<String, String> condition = dto.getCondition();
        if (condition == null || condition.isEmpty()) {
            throw new BaseException("查询参数不能为空");
        }
        String key = condition.get("key");
        if (StringUtils.isBlank(key)) {
            throw new BaseException("key不能为空");
        }
        User loginUser = userService.getLoginUser();
        if (loginUser == null) {
            throw new BaseException("请登录后进行该操作");
        }
        OtmOrderRelease release = selectById(Long.valueOf(key));
        if (release == null) {
            throw new BaseException("未查询到Key" + key + "的运单信息");
        }
        if (TableStatusEnum.STATUS_WMS_HANDOVER.getCode().equals(release.getStatus())) {
            throw new BaseException("运单" + key + "已经交验,无需重复操作");
        }
        OtmOrderRelease oor = new OtmOrderRelease();
        oor.setStatus(TableStatusEnum.STATUS_WMS_HANDOVER.getCode());
        oor.setId(release.getId());
        updateById(oor);
        release.setStatus(TableStatusEnum.STATUS_WMS_HANDOVER.getCode());
        new Thread(() -> {
            StatusLog sl = new StatusLog();
            sl.setTableType(TableStatusEnum.STATUS_10.getCode());
            sl.setTableId(String.valueOf(release.getId()));
            sl.setStatus(TableStatusEnum.STATUS_WMS_HANDOVER.getCode());
            sl.setStatusName(TableStatusEnum.STATUS_WMS_HANDOVER.getCode());
            sl.setUserCreate(loginUser.getName());
            statusLogService.insert(sl);
        }).start();
        return release;
    }

    /**
     * 装车发运 - 模糊搜索查询
     */
    @Override
    public Page<ShipmentForShipDTO> queryShipList(Page<ShipmentForShipDTO> page) {
        if (page == null) {
            throw new BaseException("page参数不能为空");
        }
        Map<String, Object> condition = page.getCondition();
        if (condition == null || condition.isEmpty()) {
            throw new BaseException("参数不能为空");
        }
        Object status = condition.get("status");
        if (status == null || StringUtils.isBlank(status.toString())) {
            throw new BaseException("状态信息不能为空");
        }
        User loginUser = userService.getLoginUser();
        if (loginUser == null) {
            throw new BaseException("请登录后进行该操作");
        }
        EntityWrapper<ShipmentForShipDTO> ew = new EntityWrapper<>();
        ew.eq("userCode", loginUser.getCode())
                .ne("releaseStatus", TableStatusEnum.STATUS_50.getCode())
                .eq("is_ship", TableStatusEnum.STATUS_1.getCode())
                .orderBy("gmt_create", false)
                .orderBy("id", false)
                .orderBy("releaseId", false)
                .groupBy("shipment_gid");
        HashMap<String, Object> params = Maps.newHashMap();
        params.put("status", status.toString());
        params.put("start", page.getOffsetCurrent());
        params.put("end", page.getSize());
        params.put("orderBy", "gmt_create desc,id desc");
        //List<ShipmentForShipDTO> list = shipmentService.queryShipmentReleaseList(page, params, ew);
        List<ShipmentForShipDTO> data = shipmentService.queryShipmentReleaseList(page, params, ew);
        ArrayList<String> gids = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(data)) {
            for (ShipmentForShipDTO dto : data) {
                gids.add(dto.getShipmentGid());
            }
            EntityWrapper<ShipmentForShipDTO> dataEW = new EntityWrapper<>();
            dataEW.in("shipment_gid", gids)
                    .eq("status", status.toString())
                    .ne("releaseStatus", TableStatusEnum.STATUS_50.getCode())
                    .eq("is_ship", TableStatusEnum.STATUS_1.getCode())
                    .orderBy("gmt_create", false)
                    .orderBy("id", false)
                    .orderBy("releaseId", false);
            List<ShipmentForShipDTO> list = shipmentService.queryShipmentReleases(dataEW);
            EntityWrapper<ShipmentForShipDTO> ttlEW = new EntityWrapper<>();
            ttlEW.eq("userCode", loginUser.getCode())
                    .ne("releaseStatus", TableStatusEnum.STATUS_50.getCode())
                    .eq("is_ship", TableStatusEnum.STATUS_1.getCode())
                    .orderBy("gmt_create", false)
                    .orderBy("id", false)
                    .orderBy("releaseId", false);
            int total = shipmentService.countShipmentReleaseList(params, ttlEW);
            //调整未查询到数据后台不抛出异常
            if (CollectionUtils.isNotEmpty(list)) {
                for (ShipmentForShipDTO dto : list) {
                    List<OtmOrderRelease> releaseList = dto.getOtmOrderReleaseList();
                    if (CollectionUtils.isEmpty(releaseList)) {
                        continue;
                    }
                    dto.setShipCount(releaseList.size());
                    int count = 0;
                    for (OtmOrderRelease release : releaseList) {
                        //已交验后状态  算作已交验数据
                        if (TableStatusEnum.STATUS_WMS_HANDOVER.getCode().equals(release.getStatus())
                                || TableStatusEnum.STATUS_BS_DISPATCH.getCode().equals(release.getStatus())
                                || TableStatusEnum.STATUS_BS_ARRIVAL.getCode().equals(release.getStatus())
                                || TableStatusEnum.STATUS_BS_POD.getCode().equals(release.getStatus())
                                || TableStatusEnum.STATUS_OR_CLOSED.getCode().equals(release.getStatus())) {
                            count++;
                        }
                    }
                    dto.setHandoverCount(count);
                }
            }
            page.setTotal(total);
            page.setRecords(list);
        }
        return page;
    }

    /**
     * 装车发运 -- 点击/扫码获取详情
     */
    @Override
    public ShipmentForShipDTO getShipDetail(AppCommonQueryDTO dto) {
        if (dto == null) {
            throw new BaseException("dto 参数不能为空");
        }
        Map<String, String> condition = dto.getCondition();
        if (null == condition || condition.isEmpty()) {
            throw new BaseException("参数不能为空");
        }
        String key = condition.get("key");
        if (StringUtils.isBlank(key)) {
            throw new BaseException("指令Id不能为空");
        }
        User loginUser = userService.getLoginUser();
        if (null == loginUser) {
            throw new BaseException("请登录后进行该操作");
        }
        EntityWrapper<ShipmentForShipDTO> ew = new EntityWrapper<>();
        ew.ne("status", TableStatusEnum.STATUS_50.getCode())
                .eq("id", key)
                .eq("userCode", loginUser.getCode())
                .ne("releaseStatus", TableStatusEnum.STATUS_50.getCode())
                .eq("is_ship", TableStatusEnum.STATUS_1.getCode())
                .orderBy("gmt_create", false)
                .orderBy("id", false)
                .orderBy("releaseId", false);
        List<ShipmentForShipDTO> list = shipmentService.getShipDetail(ew);
        if (CollectionUtils.isEmpty(list)) {
            throw new BaseException("未查询到Id" + key + "的指令信息");
        }
        if (list.size() > 1) {
            throw new BaseException("查询到Id" + key + "多条指令信息");
        }
        return list.get(0);
    }

    /**
     * 装车发运 -- 确认发运
     */
    @Override
    public ShipmentForShipDTO updateShip(AppCommonQueryDTO dto) {
        if (dto == null) {
            throw new BaseException("dto 参数不能为空");
        }
        Map<String, String> condition = dto.getCondition();
        if (null == condition || condition.isEmpty()) {
            throw new BaseException("参数不能为空");
        }
        String key = condition.get("key");
        if (StringUtils.isBlank(key)) {
            throw new BaseException("指令Id不能为空");
        }
        User loginUser = userService.getLoginUser();
        if (null == loginUser) {
            throw new BaseException("请登录后进行该操作");
        }
        EntityWrapper<ShipmentForShipDTO> ew = new EntityWrapper<>();
        ew.ne("status", TableStatusEnum.STATUS_50.getCode())
                .eq("id", key)
                .eq("userCode", loginUser.getCode())
                .ne("releaseStatus", TableStatusEnum.STATUS_50.getCode())
                .eq("is_ship", TableStatusEnum.STATUS_1.getCode())
                .orderBy("gmt_create", false)
                .orderBy("id", false)
                .orderBy("releaseId", false);
        List<ShipmentForShipDTO> list = shipmentService.getShipDetail(ew);
        if (CollectionUtils.isEmpty(list)) {
            throw new BaseException("未查询到Id" + key + "的指令信息");
        }
        if (list.size() > 1) {
            throw new BaseException("查询到Id" + key + "多条指令信息");
        }
        ShipmentForShipDTO shipDTO = list.get(0);
        OtmShipment os = new OtmShipment();
        os.setStatus(TableStatusEnum.STATUS_BS_DISPATCH.getCode());
        os.setId(shipDTO.getId());
        shipmentService.updateById(os);
        new Thread(() -> {
            StatusLog sl = new StatusLog();
            sl.setTableType(TableStatusEnum.STATUS_20.getCode());
            sl.setTableId(String.valueOf(shipDTO.getId()));
            sl.setStatus(TableStatusEnum.STATUS_BS_DISPATCH.getCode());
            sl.setStatusName(TableStatusEnum.STATUS_BS_DISPATCH.getCode());
            sl.setUserCreate(loginUser.getName());
            statusLogService.insert(sl);
        }).start();
        shipDTO.setStatus(TableStatusEnum.STATUS_BS_DISPATCH.getCode());
        //更新运单明细 状态为已发运
        List<OtmOrderRelease> releaseList = shipDTO.getOtmOrderReleaseList();
        ArrayList<StatusLog> insertLogs = Lists.newArrayList();
        for (OtmOrderRelease oor : releaseList) {
            OtmOrderRelease release = new OtmOrderRelease();
            release.setStatus(TableStatusEnum.STATUS_BS_DISPATCH.getCode());
            release.setId(oor.getId());
            updateById(release);
            oor.setStatus(TableStatusEnum.STATUS_BS_DISPATCH.getCode());
            StatusLog sl = new StatusLog();
            sl.setTableType(TableStatusEnum.STATUS_10.getCode());
            sl.setTableId(String.valueOf(release.getId()));
            sl.setStatus(TableStatusEnum.STATUS_BS_DISPATCH.getCode());
            sl.setStatusName(TableStatusEnum.STATUS_BS_DISPATCH.getCode());
            sl.setUserCreate(loginUser.getName());
            insertLogs.add(sl);
            //发运  更新车辆为已出库
            ArrayList<String> status = Lists.newArrayList();
            status.add(TableStatusEnum.STATUS_10.getCode());
            status.add(TableStatusEnum.STATUS_20.getCode());

            EntityWrapper<OutboundNoticeLine> nlEW = new EntityWrapper<>();
            nlEW.eq("line_source_key", oor.getReleaseGid())
                    .in("status", status)
                    .orderBy("id", false);
            OutboundNoticeLine noticeLine = outboundNoticeLineService.selectOne(nlEW);
            if (noticeLine != null) {
                //调用方法出库
                outboundShipLineService.shipByNoticeLineId(noticeLine.getId(), PutAwayType.NOTICE_PUTAWAY, SourceSystem.AUTO);
                //调用方法修改备料状态
                prepareHeaderService.updatePrepareFinishByLineId(noticeLine.getId(), loginUser.getName());
            }
            new Thread(() -> {
                OTMEvent otmEvent = integrationService.getOtmEvent(String.valueOf(release.getId()),
                        oor.getReleaseGid(),
                        InterfaceEventEnum.BS_OP_DELIVERY.getCode(),
                        oor.getShipmentGid(),
                        "已发运回传OTM/BMS");
                //调整参数--传递更多信息
                ShipParamDTO paramDTO = new ShipParamDTO();
                paramDTO.setPlateNo(shipDTO.getPlateNo());
                paramDTO.setTrailerNo(shipDTO.getTrailerNo());
                paramDTO.setVehicleName(oor.getStanVehicleType());
                paramDTO.setVin(oor.getVin());
                paramDTO.setOriginProvince(oor.getOriginLocationProvince());
                paramDTO.setOriginCity(oor.getOriginLocationCity());
                paramDTO.setOriginCounty(oor.getOriginLocationCounty());
                paramDTO.setOriginAddr(oor.getOriginLocationAddress());
                paramDTO.setDestProvince(oor.getDestLocationProvince());
                paramDTO.setDestCity(oor.getDestLocationCity());
                paramDTO.setDestCounty(oor.getDestLocationCounty());
                paramDTO.setDestAddr(oor.getDestLocationAddress());
                paramDTO.setDriverGid(shipDTO.getDriverGid());
                paramDTO.setProviderGid(shipDTO.getServiceProviderGid());
                paramDTO.setShipTime(String.valueOf(new Date().getTime()));
                paramDTO.setExportKey(otmEvent.getExportKey());
                paramDTO.setCallBackUrl(otmEvent.getCallBackUrl());
                paramDTO.setEventType(otmEvent.getEventType());
                paramDTO.setOccurDate(otmEvent.getOccurDate());
                paramDTO.setRecdDate(otmEvent.getRecdDate());
                paramDTO.setSort(otmEvent.getSort());
                paramDTO.setDescribe(otmEvent.getDescribe());
                paramDTO.setOrderReleaseId(otmEvent.getOrderReleaseId());
                paramDTO.setShipmentId(otmEvent.getShipmentId());
                paramDTO.setQrCode(otmEvent.getQrCode());
                paramDTO.setCusOrderNo(oor.getCusOrderNo());
                paramDTO.setCusWaybill(oor.getCusWaybillNo());
                String res = nodeExport.exportEventToOTMNew(paramDTO);
                integrationService.insertExportLogNew(String.valueOf(release.getId()),
                        paramDTO,
                        res,
                        "已发运回传OTM/BMS",
                        InterfaceEventEnum.BS_OP_DELIVERY.getCode());
            }).start();
        }
        new Thread(() -> {
            if (CollectionUtils.isNotEmpty(insertLogs)) {
                statusLogService.insertBatch(insertLogs);
            }
        }).start();
        return shipDTO;
    }

    private ReleaseWithShipmentDTO getDetailScan(String key, User loginUser) {
        EntityWrapper<ReleaseWithShipmentDTO> ew = new EntityWrapper<>();
        ew.isNotNull("userId")
                .eq("is_ship", TableStatusEnum.STATUS_1.getCode())
                .ne("status", TableStatusEnum.STATUS_50.getCode())
                .eq("userCode", loginUser.getCode())
                .andNew()
                .eq("qr_code", key)
                .or()
                .eq("vin", key)
                .or()
                .eq("cus_order_no", key)
                .orderBy("gmt_create", false)
                .orderBy("id", false);
        List<ReleaseWithShipmentDTO> data = baseMapper.getReleaseShipDetail(ew);
        if (CollectionUtils.isEmpty(data)) {
            throw new BaseException("为查询到对应发运数据");
        }
        if (data.size() > 1) {
            throw new BaseException("查询到key:" + key + "多条信息");
        }
        return data.get(0);
    }

    private ReleaseWithShipmentDTO getDetailClick(String key, User loginUser) {
        EntityWrapper<ReleaseWithShipmentDTO> ew = new EntityWrapper<>();
        ew.isNotNull("userId")
                .eq("is_ship", TableStatusEnum.STATUS_1.getCode())
                .ne("status", TableStatusEnum.STATUS_50.getCode())
                .eq("userCode", loginUser.getCode())
                .eq("id", key)
                .orderBy("gmt_create", false)
                .orderBy("id", false);
        List<ReleaseWithShipmentDTO> data = baseMapper.getReleaseShipDetail(ew);
        if (CollectionUtils.isEmpty(data)) {
            throw new BaseException("为查询到对应发运数据");
        }
        if (data.size() > 1) {
            throw new BaseException("查询到key:" + key + "多条信息");
        }
        return data.get(0);
    }

    @Override
    public void updateVin(AppCommonQueryDTO dto) {
        if (dto == null) {
            throw new BaseException("参数不能为空");
        }
        Map<String, String> condition = dto.getCondition();
        if (null == condition || condition.isEmpty()) {
            throw new BaseException("参数不能为空");
        }
        if (!condition.containsKey("key") || StringUtils.isBlank(condition.get("key"))) {
            throw new BaseException("指令id不能为空");
        }
        if (!condition.containsKey("vin") || StringUtils.isBlank(condition.get("vin"))) {
            throw new BaseException("车架号不能为空");
        }

        User loginUser = userService.getLoginUser();
        if (loginUser == null) {
            throw new BaseException("未查询到登录用户");
        }
        if (StringUtils.isBlank(loginUser.getCode())) {
            throw new BaseException("用户编码不能为空");
        }
        OtmOrderRelease orderRelease = new OtmOrderRelease();
        orderRelease.setId(Long.valueOf(condition.get("key")));
        orderRelease.setVin(condition.get("vin"));
        baseMapper.updateById(orderRelease);
        OtmOrderRelease orderReleaseResult = baseMapper.selectById(orderRelease.getId());
        // 车架号回传OTM
        sendVinBindOTM(String.valueOf(orderReleaseResult.getId()), orderReleaseResult.getVin(), orderReleaseResult);
    }

    private void sendVinBindOTM(String id, String vin, OtmOrderRelease orderReleaseResult) {
        new Thread(() -> {
            OTMEvent event = integrationService.getOtmEvent(
                    id,
                    orderReleaseResult.getReleaseGid(),
                    InterfaceEventEnum.BINDING_CODE.getCode(),
                    orderReleaseResult.getShipmentGid(),
                    "绑定车架号信息回传OTM");
            event.setVin(vin);
            String res = nodeExport.exportEventToOTM(event);
            if (StringUtils.isNotBlank(res)) {
                integrationService.insertExportLog(
                        id,
                        event,
                        res,
                        "绑定车架号信息回传OTM",
                        InterfaceEventEnum.BINDING_CODE.getCode());
            }
        }).start();
    }
}
